'''
Created on 2013. 5. 13.

@author: Lee
'''
from google.appengine.ext import ndb
from kr.community.configure import JINJA_ENVIRONMENT
from kr.community.gaesessions import get_current_session
from kr.community.models import Users
import hashlib
import webapp2

class ChangePwdPage(webapp2.RequestHandler):
    '''
        Login Page
    '''


    def get(self):
        session = get_current_session()
        template_values = {}
        template = None
        if not session.is_active():
            template = JINJA_ENVIRONMENT.get_template('result_msg.html')
            template_values['msg'] = "You're not login"
        else:
            user_key = ndb.Key(urlsafe=session['user'])
            user_entry = user_key.get()
            template_values['user'] = user_entry
            template = JINJA_ENVIRONMENT.get_template('change_pwd.html')

        self.response.write(template.render(template_values))
        
    def post(self):
        session = get_current_session()
        template_values = {}
        template = None

        if not session.is_active():
            template = JINJA_ENVIRONMENT.get_template('result_msg.html')
            template_values['msg'] = "You're not login"
        else:
            template = JINJA_ENVIRONMENT.get_template('change_pwd.html')
            user_passwd = self.request.POST['user_passwd']
            new_passwd = self.request.POST['new_passwd']
            new_passwd_cfm = self.request.POST['new_passwd_cfm']
            
            user_key = ndb.Key(urlsafe=session['user'])
            user_entry = user_key.get()
            hash_func = hashlib.md5(user_passwd)
            if (not user_passwd) or (not new_passwd) or (not new_passwd_cfm):
                template_values['error_msg'] = "Form is must fill with information."
            elif user_entry.user_passwd != hash_func.hexdigest():
                template_values['error_msg'] = "Wrong password"
            elif user_entry.user_auth == 0:
                template_values['error_msg'] = "Your account is NOT certified."
            elif new_passwd != new_passwd_cfm:
                template_values['error_msg'] = "New password is different"
            else:
                user_entry.user_passwd = hashlib.md5(new_passwd).hexdigest()
                user_entry.put()
                template_values['msg'] = "Password change is completed."
                template = JINJA_ENVIRONMENT.get_template('result_msg.html')
            
            template_values['user'] = user_entry
            
        self.response.write(template.render(template_values))